#include "RealTimeLoop.h"

// Constructor
CRealTimeLoop::CRealTimeLoop(void)
: frequency		( 60.0f )
, time0			( timeGetTime() )
, time1			( 0 )
, frameTime		( 0.0f )
, numLoops		( 0 )
, TICK_TIME		( static_cast<DWORD>( 1000.0f / frequency ) )
, MAX_LOOPS		( 1 )
, mNetworkGame	( false )
{
	// TICK_TIME Safecheck ( Each Check Cannot Be Less Than 1 Millisecond )
	if ( TICK_TIME < 1 ) this->TICK_TIME = 1;
}

// Constructor
CRealTimeLoop::CRealTimeLoop(const float f)
: frequency		( f )
, time0			( timeGetTime() )
, time1			( 0 )
, frameTime		( 0.0f )
, numLoops		( 0 )
, TICK_TIME		( static_cast<DWORD>( 1000.0f / frequency ) )
, MAX_LOOPS		( 1 )
, mNetworkGame	( false )
{
	// TICK_TIME Safecheck ( Each Check Cannot Be Less Than 1 Millisecond )
	if ( TICK_TIME < 1 ) this->TICK_TIME = 1;
}

// Destructor
CRealTimeLoop::~CRealTimeLoop(void)
{
}

// Set Frequency
void CRealTimeLoop::SetFrequency(const float f)
{
	// Set Frequency
	this->frequency = f;
	this->TICK_TIME = static_cast<DWORD>( 1000.0f / f );

	// TICK_TIME Safecheck ( Each Check Cannot Be Less Than 1 Millisecond )
	if ( TICK_TIME < 1 ) this->TICK_TIME = 1;
}

// Set Max Loops
void CRealTimeLoop::SetMaxLoops(const int l)
{
	this->MAX_LOOPS = l;
}

// Set Network Game
void CRealTimeLoop::SetNetworkGame(const bool nG)
{
	this->mNetworkGame = nG;
}

// Get Frame Delta Time ( Time Taken In The Loop )
float CRealTimeLoop::GetFrameDeltaTime(void)
{
	return ( this->frameTime / 1000.0f );
}

// Get Percent Within Tick ( Render Interpolation ) ( Account For NumLoops Overflow Causing Percent > 1 )
float CRealTimeLoop::GetPercentWithinTick(void)
{
	float percent_within_tick = static_cast<float>( ( time1 - time0 ) / TICK_TIME );
	
	if ( percent_within_tick > 1.0f ) percent_within_tick = 1.0f;

	return percent_within_tick;
}